#!/usr/bin/env bash

# redeploy https://10.68.0.1:443 deployment

test -z "${VERBOSE:-}${verbose:-}" || set -x

if [ $# -ne 2 ]
then
  echo "Usage: redeploy https://10.68.0.1:443 <deployment>"
  exit 0
fi

if [ ! -e /cm4gitlab-runner-home/kube-token ]
then
  echo "/cm4gitlab-runner-home/kube-token not found, exit."
  exit 0
fi

cp -LHvf /cm4gitlab-runner-home/kube-token /tmp/token

ts=$(date +%s)
let tsgmt=ts-28800
restarted_at=$(date +%Y-%m-%dT%H:%M:%S.%NZ -d @$tsgmt|sed -E 's#^(.{23})[0-9]{6}(.*)$#\1\2#g'|tr -d '\r\n')

IFS='' read -r -d '' token < /tmp/token
IFS='' read -r -d '' patch <<EOF
{"spec":{"template":{"metadata":{"annotations":{"kubesphere.io/restartedAt":"${restarted_at}"}}}}}
EOF

curl -X PATCH  -H "authorization: bearer ${token}" -H 'content-type: application/merge-patch+json' \
    -vskS "${1}/apis/apps/v1/namespaces/${ns:-develop}/deployments/${2}" -d "${patch}" --compressed

